#include "mainwindow.h"
#include <QDebug>
#include <QRemoteObject2.h>
#include <QROHost.h>
#include <QRONode.h>
#include <QWindow>
#include <QScreen>

#include <QApplication>

#include "RemoteTest.h"

QROHost *host = NULL;
QRONode *node = NULL;

//测试远程信号
void remoteSignalTest(){

    RemoteTest * source = new RemoteTest();

    QObject::connect(source,&RemoteTest::testSignal,[](int i,double j){
        qDebug()<<i << j<<"source";
    });

    QObject::connect(node,&QRONode::objectLinked,[=](QObject* obj){
        auto replica = qobject_cast<RemoteTest*>(obj);
        if(!replica) return;
        QObject::connect(replica,&RemoteTest::testSignal,[](int i,double j){
            qDebug()<<i << j<<"replica";
        });
        replica->emits("testSignal(int,double)",10,20.0);
    });

    host->registerObject(source);
}

//测试占领信号功能
void occupieTest(){
    RemoteTest * source = new RemoteTest();

    auto callTest = [](RemoteTest* source,RemoteTest* replica){
        bool callOnServer = false;
        if(callOnServer)
        {
            source->invoke("ownerSlot(int)",[](QVariant value,bool,QString){
                    qDebug()<<value << "source";
                },10);
        }
        else{
            replica->invoke("ownerSlot(int)",[](QVariant value,bool,QString msg){
                    qDebug()<<msg;
                    qDebug()<<value << "replica";
                },10);
        }
    };

    QObject::connect(node,&QRONode::occupiedObject,[=](QObject* obj){
        auto replica = qobject_cast<RemoteTest*>(obj);
        if(!replica) return;

        callTest(source,replica);
    });

    QObject::connect(node,&QRONode::objectLinked,[=](QObject* obj){
        auto replica = qobject_cast<RemoteTest*>(obj);
        if(!replica) return;

        QObject::connect(replica,&RemoteTest::ownerSignal,[](int n){
        qDebug()<<n << "replica";
        });

        bool doOccupy = false;
        if(doOccupy)
        {
            replica->occupy();
        }
        else{
            callTest(source,replica);
        }

    });

    host->registerObject(source);
}

//测试服务端同步槽功能
void remoteSlotTest(){
    RemoteTest * source = new RemoteTest();

    QObject::connect(node,&QRONode::objectLinked,[=](QObject* obj){
        auto replica = qobject_cast<RemoteTest*>(obj);
        if(!replica) return;
        replica->invoke("testSlot(int)",[](QVariant val,bool success,QString msg){
                qDebug()<<val;
        },10);
    });

    host->registerObject(source);
}


//测试占领同步槽功能


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QRemoteObject2::registerRemoteClass<RemoteTest>().finish();
    QRemoteObject2::registerRemoteClass<SubObjectTest>().finish();

    QString hostName = "local:ro_test";

    host = new QROHost();
    host->start(hostName);

    node = new QRONode();
    node->connectToHost(hostName);

//    remoteSignalTest();
    //remoteSlotTest();
    occupieTest();


    return a.exec();
}
